import net.spreadshirt.shop.lib.Article;

/**
 * The Articles class stores all article objects
 * and provides some methods to handle the items.
 */
class net.spreadshirt.shop.lib.Articles {

	// A list of all article items.
	private var _articles:Array;

	/**
	 * Articles Constructor
	 */
	public function Articles() {
		clear();
	}

	/**
	 * Clears all values.
	 */
	public function clear():Void {
		_articles = new Array();
	}

	/**
	 * Stores a list of article items.
	 * The old list will be overwritten.
	 * 
	 * @param	items	A list of article items.
	 */
	public function addArticles(items:Array):Void {
		// Clear articles list.
		clear();
		// Adds all items.
		for(var i:Number = 0; i < items.length; i++) {
			addArticle(items[i]);
		}
	}

	/**
	 * Stores a single article item in the articles list.
	 * 
	 * @param	item	An article item.
	 */
	public function addArticle(item:Object):Void {
		// Only adds the item if there's no other item
		// with the same article ID already stored.
		if(!isExisting(item)){
			var article:Article = new Article(item);
			_articles.push(article);
		}
	}

	/**
	 * Returns the number of stored article items.
	 * 
	 * @return	The number of items in the articles list.
	 */
	public function getCount():Number {
		return _articles.length;
	}

	/**
	 * Returns the complete list of all articles.
	 * 
	 * @return	A List of article items.
	 */
	public function getAllItems():Array {
		return _articles;
	}

	/**
	 * Returns a single article item.
	 * 
	 * @param	id	The article ID.
	 * 
	 * @return	An article item.
	 */
	public function getItem(id:Number):Article {
		var item:Article;
		for(var i:Number = 0; i < _articles.length; i++) {
			if(id == _articles[i].article_id) {
				item = _articles[i];
			}
		}
		return item;
	}

	/**
	 * Returns all articles with the requested product type ID.
	 * 
	 * @param	id	The product type ID.
	 * 
	 * @return	an array of article items
	 */
	public function getItemsByProducttype(id:Number):Array {
		var items:Array = new Array();
		for(var i:Number = 0; i < _articles.length; i++) {
			if(id == _articles[i].producttype_id) {
				items.push(_articles[i]);
			}
		}
		return items;
	}

	/**
	 * Checks if the item is already stored.
	 * 
	 * @param	item	The article item.
	 * 
	 * @return	true or false
	 */
	private function isExisting(item:Object):Boolean {
		var found:Boolean = false;
		for(var i:Number = 0; i < _articles.length; i++) {
			if(item.article_id == _articles[i].article_id) {
				found = true;
				break;
			}
		}
		return found;
	}

}
